package cate.game.pvp.championrace;

import cate.game.event.championrace.ChampionRaceTimerEvent;
import cate.game.framework.ModuleMan;
import cate.game.pvp.championrace.data.ChampionRaceMsg;

import java.util.Deque;
import java.util.List;
import java.util.concurrent.LinkedBlockingDeque;

public class GameChampionRaceRecvManager extends ModuleMan {
    private final Deque<ChampionRaceTimerEvent> events = new LinkedBlockingDeque<>();

    @Override
    public void initDependent() throws Exception {
        game.rpcRecv().onFireAndForgetTemplate(ChampionRaceMsg.TIMER_EVENT,
                ChampionRaceTimerEvent.class,
                (head, msg) -> dispatchTimerEvent(msg));
    }

    public void loadUnSolvedSpecEvents(List<ChampionRaceTimerEvent> specEvents) {
        try{
            specEvents.forEach(e -> e.setGameBody(game));
            events.addAll(specEvents);
        } catch (Exception e) {
            log.error("防止报错1", e);
        }
    }

    private void dispatchTimerEvent(ChampionRaceTimerEvent event) {
        event.setGameBody(game);
        try {
            events.add(event);
        } catch (Exception e) {
            log.error("防止报错2", e);
        }
    }

    public void tick() {
        if (events.isEmpty()) {
            return;
        }
        try{
            ChampionRaceTimerEvent event = events.pop();
            if (event != null) {
                publishEvent(game, event);
            }
        } catch (Exception e) {
            log.error("防止报错3", e);
        }
    }
}
